package com.example.httpstest;

import java.io.InputStream;
import java.security.KeyStore;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class HttpsClientActivity_bak extends Activity {
	private Button testButton;
	private String httpsUrl = "https://app-test.fisc.com.tw/smartpay/constant/constant_lastModify.xhtml";
	HttpClient hc = new DefaultHttpClient();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		testButton = (Button) findViewById(R.id.testButton);
		testButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread(){
					public void run() {
						String result = "";
						result = HttpFactory.Request(httpsUrl, new ArrayList<NameValuePair>(), null);
						Log.i("test",result  );
					};
				}.start();
			}
		});
//		testButton.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				try {
//					initKey();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//				try {
//					String result = getData(httpsUrl);
//					System.out.println("result=" + result);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		});
	}

	private void initKey() throws Exception {
		KeyStore trustStore = KeyStore.getInstance("BKS");
		// trustStore.load(
		// getBaseContext().getResources().openRawResource(
		// R.raw.server_trust), "123456".toCharArray());
		SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
		Scheme sch = new Scheme("https", socketFactory, 8443);
		hc.getConnectionManager().getSchemeRegistry().register(sch);
	}

	private String getData(String url) throws Exception {
		HttpUriRequest hr = new HttpGet(url);
		HttpResponse hres = hc.execute(hr);
		HttpEntity he = hres.getEntity();
		InputStream is = he.getContent();
		StringBuffer sb = new StringBuffer();
		byte[] bytes = new byte[1024];
		for (int len = 0; (len = is.read(bytes)) != -1;) {
			sb.append(new String(bytes, 0, len, "utf-8"));
		}
		return sb.toString();
	}
}